package cron

import (
	"time"

	"github.com/astaxie/beego"
	"publish/app/account/model"
	"publish/app/account/plat"
	"runtime/debug"
)


type AccountCrawlerWorker struct {
	ticker         *time.Ticker
	tick           int64

	countTicker         *time.Ticker
	countTick           int64
}

func (w *AccountCrawlerWorker) run() {

	w.ticker = time.NewTicker(time.Second * time.Duration(w.tick))

	for {
		select {
		case <-w.ticker.C:
			accounts, err := model.ListAccount()
			if err != nil {
				continue
			}
			beego.Info("【定时】 开始爬取各账号文章情况.")
			for i := range accounts {
				beego.Info("开始：",accounts[i].NickName,accounts[i].Plat)
				go AccountCrawler(accounts[i])
			}
		}
	}
}

func (w *AccountCrawlerWorker) run_count() {

	w.countTicker = time.NewTicker(time.Second * time.Duration(w.countTick))

	for {
		select {
		case <-w.countTicker.C:
			accounts, err := model.ListAccount()
			if err != nil {
				continue
			}
			beego.Info("【定时】 开始爬取各账号阅读情况.")
			for i, account := range accounts {
				if account.Plat == "TOUTIAO" {
					beego.Info("开始：", accounts[i].NickName, accounts[i].Plat)
					ReadCrawler(accounts[i])
				}
			}
		}
	}
}

func AccountCrawler(account model.Account){
	defer func() {
		if r := recover(); r != nil {
			debug.PrintStack()
			beego.Error("[recover]", r)
		}
	}()


	if account.Plat != "BAIJIA"{
		plat := plat.NewPlat(account.Plat)
		if plat == nil{
			beego.Error("没发现平台：",account.Plat)
			return
		}
		articles,err := plat.GetArticles(&account,time.Now().Add(-7*24*time.Hour), time.Now())
		if err != nil {
			beego.Error("平台:",account.Plat,"账号：",account.NickName,"获取文章失败")
			return
		}
		saveArticles(account,articles)
	}

	beego.Info("平台:",account.Plat,"账号：",account.NickName,"爬取文章成功")
}


func ReadCrawler(account model.Account){
	plat := plat.NewplatToutiao()
	data, err := plat.GetAllReadCount(&account)
	if err != nil {
		beego.Error("平台:",account.Plat,"账号：",account.NickName,"获取今日阅读失败")
		return
	}

	allRead := &model.AllRead{AccountId:account.Id,ReadCount:data.Count,FansCount:data.FansCount}
	if err != model.AddAllRead(allRead){
		beego.Error(err)
		return
	}

	beego.Info("平台:",account.Plat,"账号：",account.NickName,"爬取阅读成功")
}


func saveArticles(account model.Account,articles []plat.Article) {
	for _,data := range articles{
		article := model.AccountArticle{
			AccountId: account.Id,
			AccountName: account.NickName,
			Plat: account.Plat,

			ArticleId: data.ArticleId,
			Title:   data.Title,
			Url:     data.Url,
			Time:    data.Time,
			Status:  data.Status,
			FailMsg: data.FailMsg,

			RecommentCount : data.RecommentCount,
			ReadCount: data.ReadCount,
			CommentCount: data.CommentCount,
			FavCount: data.FavCount,
		}

		model.InsertOrUpdate(article)
	}
}




func StartCrawlerWorker() {
	tick := beego.AppConfig.DefaultInt64("crawler_timer_tick", 600)
	ctick := beego.AppConfig.DefaultInt64("count_crawler_timer_tick", 300)

	work := &AccountCrawlerWorker{
		tick: tick,
		countTick:ctick,
	}

	go work.run()
	go work.run_count()
}


